package cn.ygh.bbo.system.web.controller;

import cn.ygh.bbo.framerwork.core.ClientInfo;
import cn.ygh.bbo.framerwork.core.Grid;
import cn.ygh.bbo.framerwork.core.ResultAjax;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 在线用户管理
 * @author ygh
 */
@Controller
@RequestMapping("/restpage/onlineUser")
public class UserController {

    @Autowired(required = false)
    SessionDAO sessionDAO;

    /**
     * 在线用户
     * @param request 请求
     * @param response 响应
     * @param clientInfo 查询条件
     * @return
     */
    @RequiresPermissions("system:onlineUser:query")
    @ResponseBody
    @RequestMapping(value = "/query",method = RequestMethod.GET)
    public Grid grid(HttpServletRequest request, HttpServletResponse response, ClientInfo clientInfo){
        Collection<Session> activeSessions = sessionDAO.getActiveSessions();
        // 开始索引
        int fromIndex = (clientInfo.getPageNo()-1) * clientInfo.getPageSize();
        // 结束索引
        int toIndex = fromIndex + clientInfo.getPageSize();
        //最大值
        if (toIndex>activeSessions.size()){
            toIndex=activeSessions.size();
        }
        //排序
        List<Session>sessions=new ArrayList<>(activeSessions);
        sessions.sort((o1, o2) -> o2.getLastAccessTime().compareTo(o1.getLastAccessTime()));
        //分页
        List<Session>result=sessions.subList(fromIndex, toIndex);
        Grid grid=new Grid();
        grid.setTotal(activeSessions.size());
        grid.setRows(result);
        return grid;
    }

    /**
     * 强退
     * @param request 请求
     * @param response 响应
     * @return
     */
    @RequiresPermissions("system:onlineUser:del")
    @ResponseBody
    @RequestMapping(value = "/del",method = RequestMethod.POST)
    public ResultAjax del(HttpServletRequest request, HttpServletResponse response, String ids){
        String []idList=ids.split(",");
        for (String id:idList){
            Session session=new SimpleSession();
            ((SimpleSession) session).setId(id);
            sessionDAO.delete(session);
        }
        return ResultAjax.success();
    }
}
